package com.polaris.live.im.sfs.core.bean

import com.polaris.live.im.sfs.core.SmartFoxManager
import com.polaris.live.im.utils.SmartFoxUtils
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.LogExt

/**
 * 消息响应
 *
 * @author Created by lucas on 2023/10/18 20:50
 */
data class MessageResponse<R : MessageRequest>(
    /**
     * 发送的消息
     */
    val message: R,
    /**
     * 消息的回赠
     */
    val receipt: ReceiptMessage
)

data class ExtractMessageResponse<M : AbstractMessage>(
    /**
     * 发送的消息对象
     */
    val message: M,
    /**
     * 消息的回赠
     */
    val receipt: ReceiptMessage,
    /**
     * 拓展对象 json
     */
    val ext: String? = null,
)

/**
 * 解析响应
 */
inline fun <reified T : Any, reified R : MessageRequest> MessageResponse<R>.resolveResponse(): T? {
    return receipt.resolveResponse()
}

/**
 * 解析响应
 */
inline fun <reified T : Any, reified M : AbstractMessage> ExtractMessageResponse<M>.resolveResponse(): T? {
    return receipt.resolveResponse()
}

/**
 * 解析响应
 */
inline fun <reified T : Any> ReceiptMessage.resolveResponse(): T? {
    return SmartFoxUtils.fromSFSObject(sfsObject)
}

/**
 * 解析ext
 *
 * @param key 要解析的key，如果为空说明需要解析所以的对象
 */
inline fun <reified T : Any, reified R : MessageRequest> MessageResponse<R>.resolveExt(key: String?): T? {
    return receipt.resolveExt(key)
}

/**
 * 解析ext
 *
 * @param key 要解析的key，如果为空说明需要解析所以的对象
 */
inline fun <reified T : Any, reified M : AbstractMessage> ExtractMessageResponse<M>.resolveExt(key: String?): T? {
    return receipt.resolveExt(key)
}

/**
 * 解析ext
 *
 * @param key 要解析的key，如果为空说明需要解析所以的对象
 */
inline fun <reified T : Any> ReceiptMessage.resolveExt(key: String?): T? {
    if (ext == null) {
        return null
    }
    if (key == null) {
        return JsonUtils.fromJson<T>(ext)
    }

    return try {
        val objectNode = JsonParser.parseString(ext)
        if (objectNode is JsonObject) {
            val element = objectNode.get(key)
            if (element is JsonNull) {
                null
            } else {
                JsonUtils.fromJson<T>(element.toString())
            }
        } else {
            null
        }
    } catch (t: Throwable) {
        LogExt.logE(SmartFoxManager.TAG, "parse ext failure", t)
        null
    }
}